import Upload from "@/components/Upload";
import type { EditableFormInstance, ProColumns, ProFormInstance } from "@ant-design/pro-components";
import { EditableProTable, ProForm } from "@ant-design/pro-components";
import { useRequest } from "ahooks";
import { Button, Flex, message, TabsProps, Tabs } from "antd";
import React, { useEffect, useRef, useState } from "react";
import { map } from "lodash";
import { TAB_VALUES, TOTAL_TAB_VALUES } from "../constant";
import styles from "./index.module.less";

interface Props {
	getListApi: any;
	saveApi: any;
	fieldNames: {
		id: string;
		label: string;
		value: string;
	};
	keyValue?: string;
}

export default (props: Props) => {
	const { getListApi, saveApi, fieldNames, keyValue } = props;
	const [activeKey, setActiveKey] = useState(TOTAL_TAB_VALUES.eat);
	const { loading, runAsync, data } = useRequest(getListApi, { manual: true });
	const { loading: saveLoading, runAsync: saveRunAsync } = useRequest(saveApi, { manual: true });
	const [editableKeys, setEditableRowKeys] = useState<React.Key[]>([]);
	const formRef = useRef<ProFormInstance<any>>();
	const editorFormRef = useRef<EditableFormInstance<any>>();

	const columns: ProColumns<any>[] = [
		{
			title: "序号",
			dataIndex: "keyIndex",
			width: "10%",
			editable: false,
			align: "center"
		},

		{
			title: "名称",
			dataIndex: fieldNames?.label,
			formItemProps: () => {
				return {
					rules: [
						{ required: true, message: "请输入" }
						// { max: 6, message: "最多允许输6个汉字" }
					]
				};
			},
			fieldProps: {
				// showCount: true,
				// max: 6,
				// placeholder: "最多允许输6个汉字"
			},
			align: "center"
		},
		{
			title: "枚举值",
			dataIndex: fieldNames?.value,
			editable: false,
			align: "center"
		},

		{
			title: "操作",
			valueType: "option",
			width: 200,
			align: "center",
			render: (text, record, index, action) => [
				// eslint-disable-next-line react/jsx-key
				<Flex justify="center" style={{ width: "100%" }}>
					<a
						key="editable"
						onClick={() => {
							// action?.startEditable?.(record?.[fieldNames?.id]);
							if (editableKeys?.length > 0) {
								message.warning("同时只能编辑一行");
								return;
							}
							setEditableRowKeys([index]);
						}}
					>
						编辑
					</a>
				</Flex>
				// <a
				// 	key="delete"
				// 	onClick={() => {
				// 		const tableDataSource = formRef.current?.getFieldValue("table") as any[];
				// 		formRef.current?.setFieldsValue({
				// 			table: tableDataSource.filter(item => item.id !== record.id)
				// 		});
				// 	}}
				// >
				// 	删除
				// </a>
			]
		}
	];

	const initData = (data: any) => {
		formRef.current?.setFieldsValue({
			table: map(data, (item: any, index: number) => ({
				...item,
				keyIndex: index + 1
			}))
		});
	};

	useEffect(() => {
		runAsync({ category_pid: keyValue === TAB_VALUES.commodityType ? activeKey : null }).then((res: any) => {
			// console.log("======res.data:", res?.data);
			initData(res?.data);
		});
	}, [activeKey, keyValue]);

	const items: TabsProps["items"] = [
		{
			key: TOTAL_TAB_VALUES.eat,
			label: "正食",
			children: <></>
		},
		{
			key: TOTAL_TAB_VALUES.gas,
			label: "正气生活",
			children: <></>
		}
	];

	return (
		<ProForm<{
			table: any[];
		}>
			formRef={formRef}
			initialValues={{
				table: []
			}}
			submitter={false}
		>
			{keyValue === TAB_VALUES.commodityType && (
				<Tabs activeKey={activeKey} items={items} className={styles.secondTabs} type="card" onChange={t => setActiveKey(t)} />
			)}
			<EditableProTable<any>
				key={Date.now()}
				loading={loading || saveLoading}
				bordered={true}
				// rowKey={fieldNames?.id}
				scroll={{
					x: 960
				}}
				editableFormRef={editorFormRef}
				headerTitle="可编辑表格"
				// maxLength={5}
				name="table"
				recordCreatorProps={false}
				toolBarRender={false}
				columns={columns}
				value={formRef.current?.getFieldValue("table") ?? []}
				editable={{
					type: "single",
					editableKeys,
					// onChange: setEditableRowKeys,
					actionRender: (row, config, defaultDom) => {
						return [
							defaultDom.save,
							// eslint-disable-next-line react/jsx-key
							<a
								onClick={() => {
									setEditableRowKeys([]);
									initData(data?.data);
								}}
							>
								取消
							</a>
						];
					},
					onSave: async (key, record) => {
						await saveRunAsync(record);
						setEditableRowKeys([]);
						return true;
					}
					// onCancel: async () => {
					// 	setEditableRowKeys([]);
					// 	return true;
					// }
				}}
			/>
		</ProForm>
	);
};
